<?php

namespace App\Http\Controllers;

use Auth, Mail;
use App\Models\User;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    public function __construct()
    {
        // 除了。。。登录验证
        $this->middleware('auth', [
            'except' => ['show', 'create', 'store', 'index', 'confirmEmail']
        ]);

        // 已登录。。。不能注册
        $this->middleware('guest', [
            'only' => ['create', 'store']
        ]);
    }

    public function index()
    {
        $users = User::paginate();
        return view('users.index', compact('users'));
    }

    public function create()
    {
        return view('users.create');
    }

    public function show(User $user)
    {
        // todo 是否需要判断登录
        $statuses = $user->feed()->paginate();
        return view('users.show', compact('user', 'statuses'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:50',
            'email' => 'required|email|unique:users|max:255',
            'password' => 'required|confirmed|min:6'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        // 注册成功后自动登录
        $this->sendEmailConfirmationTo($user);
        session()->flash('success', '验证邮件已发送到你的注册邮箱上，请注意查收。');
        return redirect('/');
    }

    public function edit(User $user)
    {
        $this->authorize('update', $user);
        return view('users.edit', compact('user'));
    }

    public function update(Request $request, User $user)
    {
        $this->authorize('update', $user);

        $request->validate([
            'name' => 'required|max:50',
            'password' => 'nullable|confirmed|min:6'
        ]);

        $data = [
            'name' => $request->name
        ];
        if (!is_null($request->password)){
            $data['password'] = bcrypt($request->password);
        }
        $user->update($data);

        session()->flash('success', '个人资料更新成功！');
        return redirect()->route('users.show', $user);
    }

    public function destroy(User $user)
    {
        $this->authorize('destroy', $user);
        $user->delete();
        session()->flash('success', '成功删除用户！');
        return back();
    }

    protected function sendEmailConfirmationTo($user)
    {
        $view = 'emails.confirm';
        $data = compact('user');
        $to = $user->email;
        $subject = "感谢注册 Sample 应用！请确认你的邮箱。";

        Mail::send($view, $data, function($message) use ($to, $subject){
            $message->to($to)->subject($subject);
        });
    }

    public function confirmEmail($token)
    {
        $user = User::where([
            ['activation_token', $token],
            ['activated', 0]
        ])->firstOrFail();

        $user->update([
            'activation_token' => null,
            'activated' => 1
        ]);

        session()->flash('success', '恭喜你，激活成功！');
        return redirect()->route('login');
    }

    /**
     * 粉丝
     *
     * @param User $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function followers(User $user)
    {
        $users = $user->followers()->paginate();
        $title = '粉丝';
        return view('users.show_follow', compact('users', 'title'));
    }

    /**
     * 关注的人
     *
     * @param User $user
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function followings(User $user)
    {
        $users = $user->followings()->paginate();
        $title = '关注的人';
        return view('users.show_follow', compact('users', 'title'));
    }

    /**
     * 关注、取消关注用户
     *
     * @param User $user
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function follow(User $user)
    {
        if (Auth::id() === $user->id){
            return redirect('/');
        }

        Auth::user()->follow($user->id);
        return back();
    }
}
